package hypeerweb;

import communications.Command;
import communications.PeerCommunicator;

public abstract class SendVisitor implements Visitor {
	// TODO make this and all subclasses of BroadcastVisitor serializable
	
	protected static final String TARGET_KEY = "SendVisitorTarget";
	
	public SendVisitor()
	{
		
	}
	
	public static Parameters createInitialParameters(WebId targetNodeId)
	{
		Parameters parameters = new Parameters();

		parameters.set(TARGET_KEY, targetNodeId);

		return parameters;
	}
	
	protected void intermediateOperation(Node node, Parameters parameters)
	{
		
	}
	
	protected abstract void targetOperation(Node node, Parameters parameters);
	
    @Override
	public void visit(Node node, Parameters parameters)
	{
		if (node.getWebIdValue() == ((WebId)parameters.get(TARGET_KEY)).getValue())
			targetOperation(node, parameters);
		else {
			intermediateOperation(node, parameters);
			
			Node nextNode = node.closerNode((WebId) parameters.get(TARGET_KEY));
			
			if (!Node.equals(nextNode, node))
				nextNode.accept(this, parameters);
		}	
	}

    @Override
	public void visit(NodeProxy node, Parameters parameters)
	{
        String[] parameterTypeNames = new String[2];
        parameterTypeNames[0] = "hypeerweb.Visitor";
        parameterTypeNames[1] = "hypeerweb.Parameters";
        Object[] actualParameters = new Object[2];
        actualParameters[0] = this;
        actualParameters[1] = parameters;
        Command command = new Command(node.getLocalObjectId(), "hypeerweb.Node", "accept", parameterTypeNames, actualParameters, false);
        PeerCommunicator.getSingleton().sendASynchronous(node.getGlobalObjectId(), command);
	}
}
